package top.lishou.learnplat.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.lishou.learnplat.entity.DataEntity;
import top.lishou.learnplat.service.IDataService;
import top.lishou.learnplat.utils.JsonResult;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/data")
public class DataController extends BaseController {

    @Autowired
    private IDataService dataService;

    @PostMapping
    public JsonResult<Void> uploadFile(@RequestParam("file") MultipartFile file,
                                       @RequestParam("d_title") String dTitle){
        try {
            String fileAccessPath = dataService.saveUploadedFile(file, dTitle);
            return new JsonResult<>(OK);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    @GetMapping("/down/{id}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable Integer id) throws Exception {
        byte[] fileBytes = dataService.getFileById(id);

        HttpHeaders headers = new HttpHeaders();
        DataEntity dataEntity = dataService.getAllFiles().stream()
                .filter(de -> de.getId().equals(id))
                .findFirst()
                .orElse(null);

        if (dataEntity != null) {
            String fileName = dataEntity.getD_data();
            headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        }

        return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
    }

    @GetMapping("/list")
    public List<DataEntity> listFiles() {
        return  dataService.getAllFiles();
    }
}